# named pipe Server
# encoding: utf-8

import os, time
import json
from . import operation_entry

# Set communication channel to receive data/command
read_path = "/tmp/server_in.pipe"
write_path = "/tmp/server_out.pipe"

try:
    # 创建命名管道
    os.mkfifo(write_path)
    os.mkfifo(read_path)
except OSError:#, e:
    # 如果命名管道已经创建过
    print ("mkfifo error:")#,e)

# 写入和读取的文件，正好和Client相反
rf = os.open(read_path, os.O_RDONLY)
f = os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)

# prepare core algorithm module
grid_control = operation_entry.grid_control_entry()

# get request from client and process
while True:
    # 接收请求
    received_request = ''
    while True:
        s = os.read(rf, 1024)#20
        received_request = received_request + s

        print (len(s))
        # Received nothing
        if len(s) == 0:
            break

        # Reach the end
        if s[len(s)-1] == '\0':
            break

    #
    if len(received_request) == 0:
        time.sleep(1)
        continue

    # 如果收到字符,
    #print received_request
    print (len(received_request))

    # If received data is valid, call algorithms
    control_command_str = grid_control.process(received_request[0:len(received_request)-1])

    # Write command string to file
    #with open("control_output.json", "w") as write_file:
    #    json.dump(control_command_str, write_file)

    #os.write(f, "control_output.json")
    os.write(f,"%s" % control_command_str + '\0')

os.close(f)
os.close(rf)
